﻿namespace WLFramework.Web
{
    using System.Web;
    using WLFramework.Reflection.Metadata;
    using WLFramework.Web.Binder;
    using WLFramework.Web.Binder.ValueProvider;

    public static class HttpContextExtensions
    {
        public static bool AlertErrorMessage(this HttpContext context, string errorMessage)
        {
            Shield.AssertNotNull(ref context, "context");
            return context.Response.AlertErrorMessage(errorMessage);
        }

        public static TValue GetValueByName<TValue>(this HttpContext context, string name)
        {
            var providers = DefaultValueProviderFactory.GetDefaultProviders(context);
            var type = typeof(TValue);
            foreach (var provider in providers)
            {
                var result = provider.GetValue(name);
                if (result != null)
                {
                    try
                    {
                        var value = result.ConvertTo(type);
                        return (TValue)value;
                    }
                    catch
                    {
                    }
                }
            }

            return (TValue)(object)null;
        }

        public static ModelExceptionCollection GetModel<TModel>(this HttpContext context, out TModel model)
            where TModel : new()
        {
            WebModelBinder binder = new WebModelBinder();
            return binder.BindModel<TModel>(context, out model);
        }

#if FW4
        public static TValue GetValueByName<TValue>(this HttpContextBase context, string name)
        {
            var providers = DefaultValueProviderFactory.GetDefaultProviders(context);
            var type = typeof(TValue);
            foreach (var provider in providers)
            {
                var result = provider.GetValue(name);
                if (result != null)
                {
                    try
                    {
                        var value = result.ConvertTo(type);
                        return (TValue)value;
                    }
                    catch
                    {
                    }
                }
            }

            return (TValue)(object)null;
        }

        public static ModelExceptionCollection GetModel<TModel>(this HttpContextBase context, out TModel model)
            where TModel : new()
        {
            WebModelBinder binder = new WebModelBinder();
            return binder.BindModel<TModel>(context, out model);
        }
#endif

        public static HttpPostedFile GetHttpPostedFile(this HttpContext context, string key)
        {
            return context.Request.GetHttpPostedFile(key);
        }

#if FW4
        public static HttpPostedFileBase GetHttpPostedFile(this HttpContextBase context, string key)
        {
            return context.Request.GetHttpPostedFile(key);
        }
#endif
    }
}
